<?php
/*
 * 数据工厂类
 */
final class DBFactory {
	/*
	 * 当前数据库实例
	 */
	private static $db_factory;
	
	/*
	 * 配置
	 */
	private $db_config = array();
	
	/*
	 * 数据库操作实例
	 */
	private $db_list = array();

	/*
	 * 返回对象实例
	 */
	public static function get_instance($db_config = '') {
		if($db_config == '') {
			$db_config = RonBase::load_config('database');
		}
		if(DBFactory::$db_factory == '') {
			DBFactory::$db_factory = new DBFactory();
		}
		if($db_config != '' && $db_config != DBFactory::$db_factory->db_config) DBFactory::$db_factory->db_config = array_merge($db_config, DBFactory::$db_factory->db_config);
		return DBFactory::$db_factory;
	}
	
	/*
	 * 数据库操作实例
	 */
	public function get_database($db_name){
		if(!isset($this->db_list[$db_name]) || !is_object($this->db_list[$db_name])) {
			$this->db_list[$db_name] = $this->connect($db_name);
		}
		return $this->db_list[$db_name];
	}
	
	private function connect($db_name){
		$object = null;
		switch ($this->db_config[$db_name]['type']) {
			case 'mysql':
				$object = new Mysql();
				break;			
			default:
				$object = new Mysql();;
				break;
		}
		$object->open($this->db_config[$db_name]);
		return $object;
	}
	
	private function close(){
		foreach($this->db_list as $db){
			$db->close();
		}
	}
	
	public function __destruct(){
		$this->close();
	}
}